package com.orange.notificationsummary.widget;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.CallLog.Calls;
import android.text.TextUtils;

import com.orange.homescreen.pil.CallsInterface;
import com.orange.homescreen.pil.MessagesInterface;
import com.orange.homescreen.pil.PILCore;
import com.orange.homescreen.pil.PILInterfaceManager;
import com.orange.notificationsummary.NotificationGlobal;
import com.orange.notificationsummary.event.db.VoiceMailDBHelper;
import com.orange.notificationsummary.utils.Constants;
import com.orange.notificationsummary.utils.LogHelper;

/**
 * 
 * @author o
 * 
 */
public class NotificationWidgetService extends Service {

	private static final String					TAG							= "NotificationWidgetService";
	private static final String					APP_WIDGET_UPDATE_INTENT	= "com.orange.notification.UPDATE";

	// private static Context context;
	// private volatile static BasePILMonitor mMonitor;
	// private static NotificationSummaryInterface notificationInterfc;

	private volatile static WidgetUpdateHandler	mHandler;

	private static NotifSummaryObserver			notifObserver;
	private static UpdateSetting				receiver;

	private static BroadcastReceiver			voiceMailReceiver;

	class NotifSummaryObserver extends ContentObserver {
		Context	context;

		public NotifSummaryObserver(Handler handler, Context context) {
			super(handler);
			this.context = context;
		}

		public NotifSummaryObserver(Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange) {
			LogHelper.i(TAG, "onChange. ");
			performHandler(0);
		}
	}

	private class UpdateSetting extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			sendIntentForWidget(null);
		}
	}

	/**
	 * 
	 */
	// private PILListener mListener = new PILListener() {
	// @Override
	// public void update(Object data) {
	// performHandler(0);
	// }
	// };

	@Override
	public void onCreate() {
		super.onCreate();
		initialize();
		registerObserver();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		PILCore.finalize(this);
		stopMonitor();
	}

	/**
	 * 
	 */
	private void initialize() {
		if (!PILCore.isInialized()) {
			PILCore.initialize(this);
		}
		mHandler = new WidgetUpdateHandler();
	}

	/**
	 * 
	 */
	private void registerObserver() {
		notifObserver = new NotifSummaryObserver(null);
		getContentResolver().registerContentObserver(Calls.CONTENT_URI, false,
				notifObserver);
		getContentResolver().registerContentObserver(
				Uri.parse("content://mms-sms/"), false, notifObserver);

		IntentFilter filter = new IntentFilter(
				NotificationGlobal.UPDATE_SETTING_RECEIVER);
		receiver = new UpdateSetting();
		registerReceiver(receiver, filter);

		voiceMailReceiver = new VoiceMailReceiver();

		IntentFilter appChangedFilter = new IntentFilter();
		appChangedFilter.addAction(Constants.ACTION_VOICE_MAIL);
		appChangedFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		appChangedFilter.addAction(Intent.ACTION_PACKAGE_INSTALL);
		appChangedFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
		appChangedFilter.addDataScheme("package");

		registerReceiver(voiceMailReceiver, appChangedFilter);

		IntentFilter voiceMailUpdateFilter = new IntentFilter();
		voiceMailUpdateFilter.addAction(Constants.ACTION_VOICE_MAIL);

		registerReceiver(voiceMailReceiver, voiceMailUpdateFilter);
	}

	private void stopMonitor() {
		if (notifObserver != null) {
			getContentResolver().unregisterContentObserver(notifObserver);
		}
		if (receiver != null) {
			try {
				unregisterReceiver(receiver);
			} catch (Exception ex) {
				LogHelper.e(TAG, "stopMonitor. unregisterReceiver Error:", ex);
			}
		}
		if (voiceMailReceiver != null) {
			try {
				unregisterReceiver(voiceMailReceiver);
			} catch (Exception ex) {
				LogHelper.e(TAG,
						"stopMonitor. unregister voiceMail Receiver Error: ",
						ex);
			}
		}
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		try {
			switch (intent.getFlags()) {
			case 0:
				// add new APP widget
				performHandler(0);
				break;
			case 1:
				// disable widget
				stopSelf();
				break;
			default:
			}
		} catch (Exception ex) {
			LogHelper.e(TAG, "onStart. ", ex);
		}
	}

	/**
	 * 
	 */
	private void sendIntentForWidget(Message msg) {
		boolean showMessage = getSharedPreferences("notification_setting", 0)
				.getBoolean("2", true);
		boolean showMisscall = getSharedPreferences("notification_setting", 0)
				.getBoolean("0", true);
		boolean showVoicemail = getSharedPreferences(
				NotificationGlobal.NOTIFICATION_SETTING, 0).getBoolean("1",
				true);
		MessagesInterface message = (MessagesInterface) PILInterfaceManager
				.getInterface(MessagesInterface.class);

		CallsInterface call = (CallsInterface) PILInterfaceManager
				.getInterface(CallsInterface.class);
		int count = 0;
		if (showMessage) {
			count += message.getAllUnreadMessgesCount(this);
		}

		if (showMisscall) {
			count += call.getAllMissedCallsCount(this);
		}

		if (showVoicemail) {
			count += VoiceMailDBHelper.getVoiceMailInfoCount(this);
		}
		Intent intentProvider = new Intent(APP_WIDGET_UPDATE_INTENT);
		Bundle bd = new Bundle();
		bd.putInt("NotificationCount", count);
		intentProvider.putExtras(bd);
		sendBroadcast(intentProvider);
	}

	/**
	 * perform handler send message
	 * 
	 * @param appWidgetId
	 * @param contactId
	 */
	private synchronized void performHandler(int flag) {
		Message msg = mHandler.obtainMessage();
		msg.what = flag;
		mHandler.removeMessages(msg.what);
		mHandler.sendMessage(msg);
	}

	/**
	 * 
	 * @author o
	 * 
	 */
	class WidgetUpdateHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			sendIntentForWidget(msg);
		}
	}

	class VoiceMailReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Uri uri = intent.getData();
			String p = " ";
			boolean updateFlag = false;
			if (uri != null) {
				p = uri.toString();
			}
			if (!TextUtils.isEmpty(action)
					&& Constants.ACTION_VOICE_MAIL.equals(action)) {
				updateFlag = true;
			}
			if (!TextUtils.isEmpty(action)
					&& p.indexOf(Constants.PKG_VOICEMAIL) != -1) {
				updateFlag = true;
			}
			if (updateFlag && notifObserver != null) {
				notifObserver.onChange(false);
			}
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}
